package tabletask

import (
	"fmt"

	"cvevulner/cve-timed-task/db_models"
	"github.com/360EntSecGroup-Skylar/excelize/v2"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
)

func GenerateExcels(status, path string) {
	ormModel := orm.NewOrm()
	results, rowsAffected, err := db_models.GetResults(status, ormModel)
	if err != nil {
		logs.Error("db_models.GetResults error:", err)
		return
	}
	if rowsAffected == 0 {
		logs.Info("No issue record")
		return
	}

	f := excelize.NewFile()
	index := f.NewSheet("Sheet1")
	f.SetActiveSheet(index)
	cc := []string{"id", "cve_id", "cve_num", "cve_desc", "cve_level", "cve_version",
		"repair_time", "pack_name", "nvd_score", "n_vector_value", "create_time",
		"update_time", "delete_time", "status", "error_description"}
	rowBegin := "A1"
	err = f.SetSheetRow("Sheet1", rowBegin, &cc)
	if err != nil {
		logs.Error("set row title error:", err)
		return
	}

	for k, v := range results {
		rowBegin = fmt.Sprintf("A%d", k+2)
		err = f.SetSheetRow("Sheet1", rowBegin, &[]interface{}{v.IssueRecordId,
			v.CveId, v.CveNum, v.Description, v.CveLevel, v.CveVersion, v.RepairTime,
			v.PackName, v.NVDScore, v.NvectorVule, v.CreateTime, v.UpdateTime,
			v.DeleteTime, v.Status, v.ErrorDescription})
		if err != nil {
			logs.Error("f.SetSheetRow error:", err, rowBegin)
			continue
		}
	}
	err = f.SaveAs(path)
	if err != nil {
		logs.Error("f.SaveAs error: ", err, path)
	}

	err = db_models.UpdateStatue(status, ormModel)
	if err != nil {
		logs.Error("db_models.UpdateStatue error: ", err)
	}
}
